<template>
  <el-upload
    class="avatar-uploader"
    action="https://jsonplaceholder.typicode.com/posts/"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <div v-else class="txt">上传图片</div>
    <i class="el-icon-circle-close"></i>
  </el-upload>
</template>

<script>
export default {
  name: 'QuestionsUpload',
  props: {
    item: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      imageUrl: ''
    }
  },
  methods: {
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.item.img = this.imageUrl
      this.$emit('updateimg', this.item)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="less" scoped>
  .avatar-uploader {
    width: 100px;
    height: 60px;
    cursor: pointer;
    position: relative;
    margin-left: 38px;
    .txt {
      font-size: 16px;
      width: 100px;
      line-height: 60px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      &:hover {
        border-color: #409eff;
      }
    }
    .el-icon-circle-close {
      position: absolute;
      right: -8px;
      top: -8px;
      font-size: 16px;
      z-index: 99;
    }
    .avatar {
      width: 100px;
      height: 60px;
      border-radius: 6px;
    }
  }
</style>
